package cn.com.chengmandian.service;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Slf4j
@Component
public class FeignAuthInterceptor implements RequestInterceptor {
    private final static String CONTENT_LENGTH = "content-length";
    private final static String CONTENT_TYPE = "content-type";

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            if (RequestContextHolder.getRequestAttributes() != null) {
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    while (headerNames.hasMoreElements()) {
                        String name = headerNames.nextElement().toLowerCase();
                        if (name.equals(CONTENT_LENGTH) || name.equals(CONTENT_TYPE)){
                            continue;
                        }
                        requestTemplate.header(name, request.getHeader(name));
                    }
                }
            }
            requestTemplate.header(CONTENT_TYPE, "application/json"); // 防止被传递
        } catch (Exception e) {
            log.error("FeignAuthInterceptor error!", e);
        }
    }
}
